﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Dynamic;
using System.Data.SqlClient;
using System.Configuration;
using Model;
using Common;
namespace DAL
{
    public class ActiveDAL
    {
        
        public static int Save(ActiveInfo info)
        {
            string sql = string.Format("insert into [active]([UserID],[Name],[Img],[Link],[Mobile],[Context],[MoneyType],[Count],[TakeCount],[OneMoney],[AllMoney],[TakeMoney],[PrizeType],[Range],[Province],[City],[Area],[Metre],[Lat],[Lng],[Address],[State],[ClickCount],[ShareCount],[LinkText],[Degree],[Flag],[PrizeCount],[ActiveType],[NeedCount],[PrizeImg],[SkipLink],[GiftCount],[WeiXin],[Sex],[Keyword],[ShowOver],[CreateDate]) values(@UserID,@Name,@Img,@Link,@Mobile,@Context,@MoneyType,@Count,@TakeCount,@OneMoney,@AllMoney,@TakeMoney,@PrizeType,@Range,@Province,@City,@Area,@Metre,@Lat,@Lng,@Address,@State,@ClickCount,@ShareCount,@LinkText,@Degree,@Flag,@PrizeCount,@ActiveType,@NeedCount,@PrizeImg,@SkipLink,@GiftCount,@WeiXin,@Sex,@Keyword,@ShowOver,@CreateDate);select @@identity;");
            SqlParameter[] paras = new SqlParameter[]{
                new SqlParameter("@UserID", info.UserID),
                new SqlParameter("@Name", info.Name),
                new SqlParameter("@Img", info.Img),
                new SqlParameter("@Link", info.Link),
                new SqlParameter("@Mobile", info.Mobile),
                new SqlParameter("@Context", info.Context),
                new SqlParameter("@MoneyType", info.MoneyType),
                new SqlParameter("@Count", info.Count),
                new SqlParameter("@TakeCount", info.TakeCount),
                new SqlParameter("@OneMoney", info.OneMoney),
                new SqlParameter("@AllMoney", info.AllMoney),
                new SqlParameter("@TakeMoney", info.TakeMoney),
                new SqlParameter("@PrizeType", info.PrizeType),
                new SqlParameter("@Range", info.Range),
                new SqlParameter("@Province", info.Province),
                new SqlParameter("@City", info.City),
                new SqlParameter("@Area", info.Area),
                new SqlParameter("@Metre", info.Metre),
                new SqlParameter("@Lat", info.Lat),
                new SqlParameter("@Lng", info.Lng),
                new SqlParameter("@Address", info.Address),
                new SqlParameter("@State", info.State),
                new SqlParameter("@ClickCount", info.ClickCount),
                new SqlParameter("@ShareCount", info.ShareCount),
                new SqlParameter("@LinkText", info.LinkText),
                new SqlParameter("@Degree", info.Degree),
                new SqlParameter("@Flag", info.Flag),
                new SqlParameter("@PrizeCount", info.PrizeCount),
                new SqlParameter("@ActiveType", info.ActiveType),
                new SqlParameter("@NeedCount", info.NeedCount),
                new SqlParameter("@PrizeImg", info.PrizeImg),
                new SqlParameter("@SkipLink", info.SkipLink),
                new SqlParameter("@GiftCount", info.GiftCount),
                new SqlParameter("@WeiXin", info.WeiXin),
                new SqlParameter("@Sex", info.Sex),
                new SqlParameter("@Keyword", info.Keyword),
                new SqlParameter("@ShowOver", info.ShowOver),
                new SqlParameter("@CreateDate", info.CreateDate)
            };
            return DataConvert.ToInt(CommonDAL.ExecuteScalar2(sql, paras));
        }
        public static int Update(ActiveInfo info)
        {
            string sql = string.Format("update [active] set [Name]=@Name,[Img]=@Img,[Link]=@Link,[Mobile]=@Mobile,[Context]=@Context,[MoneyType]=@MoneyType,[Count]=@Count,[OneMoney]=@OneMoney,[AllMoney]=@AllMoney,[PrizeType]=@PrizeType,[Range]=@Range,[Province]=@Province,[City]=@City,[Area]=@Area,[Metre]=@Metre,[Lat]=@Lat,[Lng]=@Lng,[Address]=@Address,[LinkText]=@LinkText,[Degree]=@Degree,[PrizeCount]=@PrizeCount,[NeedCount]=@NeedCount,[PrizeImg]=@PrizeImg,[SkipLink]=@SkipLink,[GiftCount]=@GiftCount,[WeiXin]=@WeiXin,[Sex]=@Sex,[ShowOver]=@ShowOver where [ID]=@ID");
            SqlParameter[] paras = new SqlParameter[]{
                new SqlParameter("@Name", info.Name),
                new SqlParameter("@Img", info.Img),
                new SqlParameter("@Link", info.Link),
                new SqlParameter("@Mobile", info.Mobile),
                new SqlParameter("@Context", info.Context),
                new SqlParameter("@MoneyType", info.MoneyType),
                new SqlParameter("@Count", info.Count),
                new SqlParameter("@OneMoney", info.OneMoney),
                new SqlParameter("@AllMoney", info.AllMoney),
                new SqlParameter("@PrizeType", info.PrizeType),
                new SqlParameter("@Range", info.Range),
                new SqlParameter("@Province", info.Province),
                new SqlParameter("@City", info.City),
                new SqlParameter("@Area", info.Area),
                new SqlParameter("@Metre", info.Metre),
                new SqlParameter("@Lat", info.Lat),
                new SqlParameter("@Lng", info.Lng),
                new SqlParameter("@Address", info.Address),
                new SqlParameter("@LinkText", info.LinkText),
                new SqlParameter("@Degree", info.Degree),
                new SqlParameter("@PrizeCount", info.PrizeCount),
                new SqlParameter("@NeedCount", info.NeedCount),
                new SqlParameter("@PrizeImg", info.PrizeImg),
                new SqlParameter("@SkipLink", info.SkipLink),
                new SqlParameter("@GiftCount", info.GiftCount),
                new SqlParameter("@WeiXin", info.WeiXin),
                new SqlParameter("@Sex", info.Sex),
                new SqlParameter("@ShowOver", info.ShowOver),
                new SqlParameter("@ID", info.ID)
            };
            return CommonDAL.ExecuteNoneQuery(sql, paras) ? info.ID : 0;
        }
        public static int Edit(ActiveInfo info)
        {
            string sql = string.Format("update [active] set [Name]=@Name,[Img]=@Img,[Context]=@Context,[PrizeType]=@PrizeType,[ClickCount]=@ClickCount,[ShareCount]=@ShareCount,[Link]=@Link,[Mobile]=@Mobile,[TakeCount]=@TakeCount,[TakeMoney]=@TakeMoney,[ShowOver]=@ShowOver where [ID]=@ID");
            SqlParameter[] paras = new SqlParameter[]{
                new SqlParameter("@Name", info.Name),
                new SqlParameter("@Img", info.Img),
                new SqlParameter("@Context", info.Context),
                new SqlParameter("@PrizeType", info.PrizeType),
                new SqlParameter("@ClickCount", info.ClickCount),
                new SqlParameter("@ShareCount", info.ShareCount),
                new SqlParameter("@Link",info.Link),
                new SqlParameter("@Mobile",info.Mobile),
                new SqlParameter("@TakeCount", info.TakeCount),
                new SqlParameter("@TakeMoney", info.TakeMoney),
                new SqlParameter("@ShowOver", info.ShowOver),
                new SqlParameter("@ID", info.ID)
            };
            return CommonDAL.ExecuteNoneQuery(sql, paras) ? info.ID : 0;
        }
        public static bool UpdateLinkText(int id, string linktext)
        {
            string sql = string.Format("update [active] set [LinkText]=@LinkText where [ID]=@ID");
            SqlParameter[] paras = new SqlParameter[]{
                new SqlParameter("@LinkText", linktext),
                new SqlParameter("@ID", id)
            };
            return CommonDAL.ExecuteNoneQuery(sql, paras);
        }
        public static bool UpdateTakeMoney(int id, double money)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update active set TakeCount=TakeCount+1,TakeMoney=TakeMoney+{0} where ID={1}", money, id));
        }
        public static bool UpdateTakeMoney(int id, int count, double money)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update active set TakeCount=TakeCount+{0},TakeMoney=TakeMoney+{1} where ID={2}", count, money, id));
        }
        public static bool UpdateTakeGiftCount(int id)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update active set TakeGiftCount=TakeGiftCount+1 where ID={0}", id));
        }
        public static bool IncClickCount(int id)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set ClickCount=ClickCount+1 where ID={0}", id));
        }
        public static bool IncClickCount(int id, int count)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set ClickCount=ClickCount+{1} where ID={0}", id,count));
        }
        public static bool IncShareCount(int id)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set ShareCount=ShareCount+1 where ID={0}", id));
        }
        public static bool IncShareCount(int id, int count)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set ShareCount=ShareCount+{1} where ID={0}", id,count));
        }
        public static bool IncPraiseCount(int id)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set PraiseCount=PraiseCount+1 where ID={0}", id));
        }
        public static bool Finish(int id)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set TakeCount=Count,TakeMoney=AllMoney where ID={0}", id));
        }
        public static ActiveInfo FindOneByID(int id)
        {
            DataRow dr = CommonDAL.FindOneByID(id, "[active]");
            return Simple_Data(dr);
        }
        public static List<ActiveInfo> FindListByIDs(string ids)
        {
            DataTable dt = CommonDAL.FindListByIDs(ids, "[active]");
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(Simple_Data(row));
            }
            return list;
        }
        public static List<ActiveInfo> FindPage(string keyword, int userid, int startindex, int pagesize, string order, string desc, out int count)
        {
            string filter = " and UserID="+userid;
            DataTable dt = CommonDAL.FindPage(startindex, pagesize, order, desc, filter, "[active]", out count);
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(Simple_Data(row));
            }
            return list;
        }
        public static List<ActiveInfo> FindPage(string keyword, int flag, int state, int type, string begindate, string enddate, int startindex, int pagesize, string order, string desc, out int count)
        {
            string filter = "";
            if (flag != 0)
            {
                //filter += " and Flag=" + flag;
            }
            if (type != -1)
            {
                filter += " and ActiveType=" + type;
            }
            if (B.MyAdmin.Role == 2)
            {
                string adminids = string.Join(",", AdminDAL.FindAllChildByID(B.MyAdmin.ID).Select(x => x.ID));
                if (!string.IsNullOrEmpty(adminids))
                {
                    filter += " and [admin].ID in (" + adminids + ")";
                }
                else
                {
                    filter += " and 1=2";
                }
            }
            if (state != -1)
            {
                filter += " and [active].State=" + state;
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += " and ([active].Name like '%" + keyword + "%' or [user].NickName like '%" + keyword + "%')";
            }
            if (!string.IsNullOrEmpty(begindate) && !string.IsNullOrEmpty(enddate))
            {
                filter += " and [active].CreateDate between '" + DataConvert.ToDateTime(begindate).ToString("yyyy-MM-dd 00:00:00") + "' and '" + DataConvert.ToDateTime(enddate).ToString("yyyy-MM-dd 23:59:59") + "'";
            }
            DataTable dt = CommonDAL.FindCPage(startindex, pagesize, order, desc, filter, "[active_page]", out count);
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(All_Data(row));
            }
            return list;
        }
        public static List<ActiveInfo> FindBatchList(string keyword, int flag, int state, int type, string begindate, string enddate)
        {
            string filter = "";
            if (flag != 0)
            {
                //filter += " and Flag=" + flag;
            }
            if (type != -1)
            {
                filter += " and ActiveType=" + type;
            }
            if (B.MyAdmin.Role == 2)
            {
                string adminids = string.Join(",", AdminDAL.FindAllChildByID(B.MyAdmin.ID).Select(x => x.ID));
                if (!string.IsNullOrEmpty(adminids))
                {
                    filter += " and [admin].ID in (" + adminids + ")";
                }
                else
                {
                    filter += " and 1=2";
                }
            }
            if (state != -1)
            {
                filter += " and [active].State=" + state;
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += " and ([active].Name like '%" + keyword + "%' or [user].NickName like '%" + keyword + "%')";
            }
            if (!string.IsNullOrEmpty(begindate) && !string.IsNullOrEmpty(enddate))
            {
                filter += " and [active].CreateDate between '" + DataConvert.ToDateTime(begindate).ToString("yyyy-MM-dd 00:00:00") + "' and '" + DataConvert.ToDateTime(enddate).ToString("yyyy-MM-dd 23:59:59") + "'";
            }
            DataTable dt = CommonDAL.GetDataTable(string.Format("select * from [active] where 1=1 {0} order by id desc", filter.ToString()));
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(Simple_Data(row));
            }
            return list;
        }
        public static List<ActiveInfo> FindPage2(string keyword, int flag, string begindate, string enddate, int startindex, int pagesize, string order, string desc, out int count)
        {
            string filter = " and [active].UserID=" + B.MyUser.ID;
            
            if (flag != 0)
            {
                filter += " and [active].Flag=" + flag;
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += " and ([active].Name like '%" + keyword + "%' or [user].NickName like '%" + keyword + "%')";
            }
            if (!string.IsNullOrEmpty(begindate) && !string.IsNullOrEmpty(enddate))
            {
                filter += " and [active].CreateDate between '" + DataConvert.ToDateTime(begindate).ToString("yyyy-MM-dd 00:00:00") + "' and '" + DataConvert.ToDateTime(enddate).ToString("yyyy-MM-dd 23:59:59") + "'";
            }
            DataTable dt = CommonDAL.FindCPage(startindex, pagesize, order, desc, filter, "[active_page]", out count);
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(All_Data(row));
            }
            return list;
        }
        public static List<ActiveInfo> FindAll(int flag)
        {
            DataTable dt = CommonDAL.GetDataTable(string.Format("select * from [active] where Flag={0}", flag));
            List<ActiveInfo> list = new List<ActiveInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(Simple_Data(row));
            }
            return list;
        }
        private static ActiveInfo Simple_Data(DataRow dr)
        {
            ActiveInfo info = new ActiveInfo();
            if (dr != null)
            {
                info.ID = DataConvert.ToInt(dr["ID"]);
                info.UserID = DataConvert.ToInt(dr["UserID"]);
                info.Name = DataConvert.ToString(dr["Name"]);
                info.Img = Commons.domain + DataConvert.ToString(dr["Img"]);
                info.Ewm = Commons.domain + DataConvert.ToString(dr["Ewm"]);
                info.Link = DataConvert.ToString(dr["Link"]);
                info.Mobile = DataConvert.ToString(dr["Mobile"]);
                info.Context = DataConvert.ToString(dr["Context"]).Replace("\"","");
                info.MoneyType = DataConvert.ToInt(dr["MoneyType"]);
                info.Count = DataConvert.ToInt(dr["Count"]);
                info.TakeCount = DataConvert.ToInt(dr["TakeCount"]);
                info.OneMoney = DataConvert.ToFloat(dr["OneMoney"])/100;
                info.AllMoney = DataConvert.ToFloat(dr["AllMoney"]) / 100;
                info.TakeMoney = DataConvert.ToFloat(dr["TakeMoney"]) / 100;
                info.PrizeType = DataConvert.ToInt(dr["PrizeType"]);
                info.Range = DataConvert.ToInt(dr["Range"]);
                info.Province = DataConvert.ToString(dr["Province"]);
                info.City = DataConvert.ToString(dr["City"]);
                info.Area = DataConvert.ToString(dr["Area"]);
                info.Metre = DataConvert.ToFloat(dr["Metre"]);
                info.Lat = DataConvert.ToFloat(dr["Lat"]);
                info.Lng = DataConvert.ToFloat(dr["Lng"]);
                info.Address = DataConvert.ToString(dr["Address"]);
                info.State = DataConvert.ToInt(dr["State"]);
                info.ClickCount = DataConvert.ToInt(dr["ClickCount"]);
                info.ShareCount = DataConvert.ToInt(dr["ShareCount"]);
                info.PraiseCount = DataConvert.ToInt(dr["PraiseCount"]);
                info.LinkText = DataConvert.ToString(dr["LinkText"]);
                info.Degree = DataConvert.ToInt(dr["Degree"]);
                info.IsAuto = DataConvert.ToInt(dr["IsAuto"]);
                info.PrizeCount = DataConvert.ToInt(dr["PrizeCount"]);
                info.ActiveType = DataConvert.ToInt(dr["ActiveType"]);
                info.NeedCount = DataConvert.ToInt(dr["NeedCount"]);
                info.PrizeImg = DataConvert.ToString(dr["PrizeImg"]);
                info.SkipLink = DataConvert.ToString(dr["SkipLink"]);
                info.GiftCount = DataConvert.ToInt(dr["GiftCount"]);
                info.TakeGiftCount = DataConvert.ToInt(dr["TakeGiftCount"]);
                info.WeiXin = Commons.domain + DataConvert.ToString(dr["WeiXin"]);
                info.Sex = DataConvert.ToInt(dr["Sex"]);
                info.Keyword = DataConvert.ToString(dr["Keyword"]);
                info.ShowOver = DataConvert.ToInt(dr["ShowOver"]);
                info.CreateDate = DataConvert.ToDateTime(dr["CreateDate"]);

                info.StateText = Commons.ActiveState[info.State];
                info.PrizeTypeText = Commons.PrizeType[info.PrizeType];
            }
            return info;
        }
        private static ActiveInfo All_Data(DataRow dr)
        {
            ActiveInfo info = new ActiveInfo();
            if (dr != null)
            {
                info.ID = DataConvert.ToInt(dr["ID"]);
                info.UserID = DataConvert.ToInt(dr["UserID"]);
                info.Name = DataConvert.ToString(dr["Name"]);
                info.Img = Commons.domain + DataConvert.ToString(dr["Img"]);
                info.Ewm = Commons.domain + DataConvert.ToString(dr["Ewm"]);
                info.Link = DataConvert.ToString(dr["Link"]);
                info.Mobile = DataConvert.ToString(dr["Mobile"]);
                info.Context = DataConvert.ToString(dr["Context"]);
                info.MoneyType = DataConvert.ToInt(dr["MoneyType"]);
                info.Count = DataConvert.ToInt(dr["Count"]);
                info.TakeCount = DataConvert.ToInt(dr["TakeCount"]);
                info.OneMoney = DataConvert.ToFloat(dr["OneMoney"]) / 100;
                info.AllMoney = DataConvert.ToFloat(dr["AllMoney"]) / 100;
                info.TakeMoney = DataConvert.ToFloat(dr["TakeMoney"]) / 100;
                info.PrizeType = DataConvert.ToInt(dr["PrizeType"]);
                info.Range = DataConvert.ToInt(dr["Range"]);
                info.Province = DataConvert.ToString(dr["Province"]);
                info.City = DataConvert.ToString(dr["City"]);
                info.Area = DataConvert.ToString(dr["Area"]);
                info.Metre = DataConvert.ToFloat(dr["Metre"]);
                info.Lat = DataConvert.ToFloat(dr["Lat"]);
                info.Lng = DataConvert.ToFloat(dr["Lng"]);
                info.Address = DataConvert.ToString(dr["Address"]);
                info.State = DataConvert.ToInt(dr["State"]);
                info.ClickCount = DataConvert.ToInt(dr["ClickCount"]);
                info.ShareCount = DataConvert.ToInt(dr["ShareCount"]);
                info.PraiseCount = DataConvert.ToInt(dr["PraiseCount"]);
                //info.LinkText = DataConvert.ToString(dr["LinkText"]);
                info.Degree = DataConvert.ToInt(dr["Degree"]);
                info.IsAuto = DataConvert.ToInt(dr["IsAuto"]);
                info.PrizeCount = DataConvert.ToInt(dr["PrizeCount"]);
                info.ActiveType = DataConvert.ToInt(dr["ActiveType"]);
                info.NeedCount = DataConvert.ToInt(dr["NeedCount"]);
                info.PrizeImg = Commons.domain + DataConvert.ToString(dr["PrizeImg"]);
                info.SkipLink = DataConvert.ToString(dr["SkipLink"]);
                info.GiftCount = DataConvert.ToInt(dr["GiftCount"]);
                info.TakeGiftCount = DataConvert.ToInt(dr["TakeGiftCount"]);

                if (info.ActiveType == 2)
                {
                    info.TakeCount = info.TakeGiftCount;
                    info.Count = info.GiftCount;
                }
                info.WeiXin = Commons.domain + DataConvert.ToString(dr["WeiXin"]);
                info.Sex = DataConvert.ToInt(dr["Sex"]);
                info.CreateDate = DataConvert.ToDateTime(dr["CreateDate"]);

                info.StateText = Commons.ActiveState[info.State];
                info.PrizeTypeText = Commons.PrizeType[info.PrizeType];
                info.NickName = DataConvert.ToString(dr["NickName"]);
                info.IDPwd = DESEncrypt.Encrypt(info.ID.ToString());
                info.Keyword = DataConvert.ToString(dr["Keyword"]);
                info.ShowOver = DataConvert.ToInt(dr["ShowOver"]);
            }
            return info;
        }

        public static void DecClickCount()
        {
            List<ReduceInfo> reducelist = ReduceDAL.FindListOfRun();
            List<ActiveInfo> activelist = ActiveDAL.FindListByIDs(string.Join(",", reducelist.Select(x => x.ActiveID)));
            foreach (ReduceInfo info in reducelist)
            {
                int minute = Commons.DateDiff(info.LastEditTime, DateTime.Now, "S");
                int increasecount = (int)(DataConvert.ToDecimal(info.HourCount)/3600*minute);
                ActiveInfo active = B.Instance<ActiveInfo>(activelist.FirstOrDefault(x => x.ID == info.ActiveID));
                if(increasecount>0)
                {
                    VisitRecordInfo visit = new VisitRecordInfo()
                    {
                        UserID = 0,
                        SID = info.ActiveID,
                        Province = "",
                        City = "",
                        Area = "",
                        Lat = 0,
                        Lng = 0,
                        Address = "",
                        CreateID = active.UserID,
                        FCount = increasecount,
                        Flag = 1,
                        CreateDate = DateTime.Now
                    };
                    VisitRecordDAL.Save(visit);
                    ActiveDAL.IncClickCount(active.ID, increasecount);
                    ReduceDAL.DecReduce(info.ID);
                }
            }
        }
        public static bool SetSynch(int olduserid,int newuserid)
        {
            return CommonDAL.ExecuteNoneQuery(string.Format("update [active] set UserID={0} where UserID={1}", newuserid, olduserid));
        }
    }
}
